package com.req.vmsg.processor;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.req.vmsg.util.TxtWebConstants;
import com.util.vmsg.beans.MobileNumber;
import com.util.vmsg.beans.TxtWebMessage;
import com.util.vmsg.beans.TxtWebResponse;
import com.util.vmsg.beans.Vehicle;
import com.vutil.src.dao.VMsgDAO;

public class VMsgProcessor {
	
	public TxtWebResponse processRegistration(TxtWebMessage txtWebMsg)
	{
		TxtWebResponse txtWebResponse = new TxtWebResponse();
		
		VMsgDAO vMsgDAO = VMsgDAO.getInstance();
		
		String txtMsg = txtWebMsg.getTxtWebMessage();
		String[] msgTokens = txtMsg.split(TxtWebConstants.Grammer.SPACE);
		
		Vehicle vehicle = new Vehicle(msgTokens[1]);
		MobileNumber mobileNumber = new MobileNumber(txtWebMsg.getTxtWebMobileNumber(),true, null);
		
		boolean isExistingMobileNumber = vMsgDAO.isExistingMobileNumber(mobileNumber);
		if(!isExistingMobileNumber)
			vMsgDAO.create(mobileNumber);
		
		boolean isExistingVehicle = vMsgDAO.isExistingVehicleNumber(vehicle);
		if(!isExistingVehicle)
		{
			List<MobileNumber> vMsgSubscribers = new ArrayList<MobileNumber>();
			vMsgSubscribers.add(mobileNumber);
			vehicle.setvMsgSubscribers(vMsgSubscribers);
			
			vMsgDAO.create(vehicle);
		}
		
		boolean isAlreadySubscribed = vMsgDAO.checkDupeSubscription(vehicle, mobileNumber);
		if(!isAlreadySubscribed)
			vMsgDAO.updateVMsgSubscriberList(vehicle,mobileNumber);
		
		txtWebResponse.setMobileId(txtWebMsg.getTxtWebMobileNumber());
		txtWebResponse.setMessage(TxtWebConstants.VMsgHelpMessages.REGISTERED_SUCCESSFULLY + vehicle.getVehicleNumber());
		return txtWebResponse;
	}
	
	public void processForceRegistration(TxtWebMessage txtWebMsg)
	{
		
	}
	
	public void forwardVMsg(TxtWebMessage txtWebMessage)
	{
		String txtMsg = txtWebMessage.getTxtWebMessage();
		String[] msgTokens = txtMsg.split(TxtWebConstants.Grammer.SPACE);
		
		Vehicle vehicle = new Vehicle(msgTokens[0]);
		
		VMsgDAO vMsgDAO = VMsgDAO.getInstance();
		List<MobileNumber> vMsgSubscriptionList = vMsgDAO.getVehicleNumberSubscriptionList(vehicle);
		for(MobileNumber mobileNumber : vMsgSubscriptionList)
		{
			TxtWebResponse txtWebResponse = new TxtWebResponse(); 
			txtWebResponse.setMessage(txtWebMessage.getTxtWebMessage());
			txtWebResponse.setMobileId(mobileNumber.getMobileNumber());
			sendVMsg(txtWebResponse);
		}
	}
	
	public void relayHelpMessage(TxtWebMessage txtWebMsg)
	{
		
	}
	
	public void relayCustomMessage(TxtWebMessage txtWebMsg)
	{
		
	}
	
	public void processDeregistration(TxtWebMessage txtWebMsg)
	{
		
	}

	public void processForceDeregistration(TxtWebMessage txtWebMsg)
	{
		
	}

	public void sendVMsg(TxtWebResponse txtWebResponse)
	{
		VMsgResponder vMsgResponder = new VMsgResponder();
		vMsgResponder.relayVMsg(txtWebResponse.getMobileId(), txtWebResponse.getMessage());
	}
}
